package com.vinaprime.primeschedule.presentation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TimePicker;

import com.vinaprime.primeschedule.businesslayer.VPEvent_BL;
import com.vinaprime.primeschedule.entities.VPEvent;

public class VPEventActivity extends Activity {
	private ApplicationInformation myAppInfo;
	private String myPath;
	
	private List<VPEvent> myListEvent;
	private VPEvent_BL myEventBL;
	private ListView myListView;
	private VPEventActivityAdapter myListViewAdapter;
	private Date myCurrentDate;
	private int myPositionCurrentOfList;
	
	private Calendar myCalendar;
	private SimpleDateFormat myDateFormat = null;
	private int mDateDialogId;
	private static final int DATE_DIALOG_TYPE = 5;
	private static final int DATE_DIALOG_ID = 0;
	private static final int TIME_DIALOG_TYPE = 1;
	private static final int TIME_DIALOG_ID = 999;
	
	private EditText myEdtTitleName;
	private EditText myEdtAddress;
	private EditText myEdtLocation;	
	private EditText myEdtDescription;
	private Button myBtnStartDate;
	private Button myBtnEndDate;	
	private Button myBtnStartTime;
	private Button myBtnEndTime;
	private Button myBtnOK;
	private Button myBtnCancel;
	private ImageButton myBtnMap;
	private TabHost tab;
	private int myHour, myMinute;
	private static final int MAP_SELECT =1;
	private Uri myMapUri;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpevent);
		
		//ACtion bar
		ActionBar actionBar = getActionBar();
		Drawable d=getResources().getDrawable(R.drawable.background_top_shape_green);  
		actionBar.setBackgroundDrawable(d);    
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
		loadTabs();	
	   	}
	@SuppressWarnings("static-access")
	public void showlistview() throws IllegalArgumentException, ParseException{
		myListEvent = myEventBL.getEventbyDate(myCurrentDate);
		myListView = (ListView)findViewById(R.id.lvSnoozeSound);
		myListView.setChoiceMode(myListView.CHOICE_MODE_SINGLE);		
		myListViewAdapter = new VPEventActivityAdapter(myListEvent, this, myPath + "databases/");		
		myListView.setAdapter(myListViewAdapter);
		//
		myListView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unused")
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
				VPEvent myEvent = new VPEvent(); 
				myEvent = myListEvent.get(position);
				
			    arg0.getChildAt(myPositionCurrentOfList).setBackgroundResource(R.color.White);
			    myPositionCurrentOfList =  position;						
			
				myListView.setItemChecked(myPositionCurrentOfList, true);
				
				myListViewAdapter.setMyLastSelectedPostition(myPositionCurrentOfList);
			}
		});
		myListView.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				registerForContextMenu(myListView);
				return false;
			}
		});
	}
	public void loadTabs(){
		
		 tab=(TabHost) findViewById (android.R.id.tabhost);
		 tab.setup();
		 Drawable d=getResources().getDrawable(R.drawable.background_shape_white);  
		 tab.setBackgroundDrawable(d);
		 TabHost.TabSpec spec;
		 // tab1
		 spec=tab.newTabSpec("t1");
		 spec.setContent(R.id.tab1);
		 spec.setIndicator("Incomplete");		 
		 tab.addTab(spec);
		 // tab2
		 spec=tab.newTabSpec("t2");
		 spec.setContent(R.id.tab2);
		 spec.setIndicator("Completed");
		 tab.addTab(spec);
		 
		 tab.setCurrentTab(0);
		
	}
  
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.vpevent, menu);
		
		return true;
	}
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.action_add:
	      	 showDialogAddEvent();
	      break;	    
	    default:
	    	break;
	    }
	    return true;
	  }
	
	
    
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			 ContextMenuInfo menuInfo) 
	{
			 // TODO Auto-generated method stub
			 super.onCreateContextMenu(menu, v, menuInfo);			
			 getMenuInflater().inflate(R.menu.vpcontact_context, menu);
			 menu.setHeaderTitle(R.string.ctx_action_title);
			 
	}
	public void getDefaultDialogInfo(){
	    	myCalendar = Calendar.getInstance(); 			
			//Lay ngay he thong
			myCurrentDate = new Date(System.currentTimeMillis());
			
			myDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
			myBtnStartDate.setText(myDateFormat.format(myCurrentDate.getTime()));
			myBtnEndDate.setText(myDateFormat.format(myCurrentDate.getTime()));
			myDateFormat =  new SimpleDateFormat("HH:mm",Locale.getDefault());
			myBtnStartTime.setText(myDateFormat.format(myCurrentDate.getTime()));
			myBtnEndTime.setText(myDateFormat.format(myCurrentDate.getTime()));
			
	}
	private void showDialogAddEvent() {
		// TODO Auto-generated method stub	

		//textEntryView.setBackgroundResource(R.drawable.background_shape_gray);		

		AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.customalertdialog);       
		
		LayoutInflater inflaterTitle =  getLayoutInflater();
		View myTitleview = inflaterTitle.inflate(R.layout.dialog_context_title, null);			
		
		builder.setCustomTitle(myTitleview);	
		
		View entryView = inflaterTitle.inflate(R.layout.dialog_add_event, null);
		builder.setView(entryView);
		
        /*    */
        
        final AlertDialog alert = builder.create();
		alert.show();
		
		myBtnStartTime = (Button)alert.findViewById(R.id.btnEventStartTime);
		myBtnEndTime = (Button)alert.findViewById(R.id.btnEventEndTime);
		myBtnStartDate = (Button)alert.findViewById(R.id.btnEventStartDate);
  	    myBtnEndDate = (Button)alert.findViewById(R.id.btnEventEndDate);	 
		myBtnMap = (ImageButton)alert.findViewById(R.id.btnMap);
		myEdtTitleName = (EditText)alert.findViewById(R.id.edteTitle);
		myEdtAddress = (EditText)alert.findViewById(R.id.edteAdress);
		myEdtLocation =(EditText)alert.findViewById(R.id.edteLocation);		 
		myEdtDescription = (EditText)alert.findViewById(R.id.edteDescription);
		myBtnOK = (Button)alert.findViewById(R.id.btnEventOK);
		myBtnCancel= (Button)alert.findViewById(R.id.btnEventCancel);
		getDefaultDialogInfo();
        myBtnMap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Toast.makeText(getApplicationContext(), "ADD", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(getApplicationContext(), VPEventMap.class);
				startActivityForResult(intent, MAP_SELECT);
			}
		});
        
        myBtnStartDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDateDialogId = 0;
				showDialog(DATE_DIALOG_ID);
				
			}
		});
    	myBtnEndDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDateDialogId = 1;
				showDialog(DATE_DIALOG_ID);
				
			}
		});
        myBtnStartTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDateDialogId = 2;
				showDialog(TIME_DIALOG_ID);
			}
		});
        myBtnEndTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDateDialogId = 3;
				showDialog(TIME_DIALOG_ID);
			}
		});
    	myBtnOK.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				return;
			}

			
		});
    	myBtnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				alert.cancel();
			}

			
		});
  	    Resources resource = alert.getContext().getResources();
		/*int titledividerid = resource.getIdentifier("titleDivider", "id", "android");
		View titledivider = alert.getWindow().getDecorView().findViewById(titledividerid);
		titledivider.setBackgroundResource(android.R.color.transparent);			*/
		alert.getWindow().setBackgroundDrawableResource(android.R.color.transparent);		
		
		
	}
	private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                	myCalendar.set(Calendar.YEAR, year);
                	myCalendar.set(Calendar.MONTH, monthOfYear);
                	myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateDisplay();                    
                }
            };
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id){
        case DATE_DIALOG_ID:
	    	return new DatePickerDialog(this, DATE_DIALOG_TYPE,
	                            mDateSetListener,
	                            myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
	        
        case TIME_DIALOG_ID:
        	return new TimePickerDialog(this, TIME_DIALOG_TYPE, 
        							mTimeSetListener, 
        							myCalendar.HOUR_OF_DAY,
        							myCalendar.MINUTE, false);
        }
        return null;
    }
    
    private void updateDisplay() {
      // Toast.makeText(getApplicationContext(), ""+mDateDialogId, Toast.LENGTH_SHORT).show();
    	switch (mDateDialogId) {
		case 0:
			myDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());			
			myBtnStartDate.setText(this.myDateFormat.format(this.myCalendar.getTime()));
			
			break;
		case 1:
			myDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());		
			myBtnEndDate.setText(this.myDateFormat.format(this.myCalendar.getTime()));
			break;
		case 2:
			myDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());	
			
			myBtnStartTime.setText(this.myDateFormat.format(this.myCalendar.getTime()));
			//Toast.makeText(getApplicationContext(), this.myDateFormat.format(this.myCalendar.getTime()), Toast.LENGTH_SHORT).show();
			break;
		case 3:
			//Toast.makeText(getApplicationContext(), "3"+this.myDateFormat.format(this.myCalendar.getTime()), Toast.LENGTH_SHORT).show();
			myDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
			myBtnEndTime.setText(this.myDateFormat.format(this.myCalendar.getTime()));
			//Toast.makeText(getApplicationContext(), this.myDateFormat.format(this.myCalendar.getTime()), Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
    	
    }
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = 
    		new TimePickerDialog.OnTimeSetListener() {
				
				@Override
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					// TODO Auto-generated method stub
					myCalendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
					myCalendar.set(Calendar.MINUTE, minute);
					updateDisplay();
					
				}
			};
	
	public void onActivityResult(int requestCode, int resultCode, Intent data){
				super.onActivityResult(requestCode, resultCode, data);			
				myMapUri  =  data.getData();
				if (resultCode == RESULT_OK ){					
					switch (requestCode) {
					case MAP_SELECT:						
						break;
					
					
					default:				
						break;
					}
				}
			}
    public void setCurrentDateTimeonView(){
    	/*tvDisplayTime = (TextView) findViewById(R.id.tvTime);
		timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
 
		final Calendar c = Calendar.getInstance();
		hour = c.get(Calendar.HOUR_OF_DAY);
		minute = c.get(Calendar.MINUTE);
 
		// set current time into textview
		tvDisplayTime.setText(
                    new StringBuilder().append(pad(hour))
                                       .append(":").append(pad(minute)));
 
		// set current time into timepicker
		timePicker1.setCurrentHour(hour);
		timePicker1.setCurrentMinute(minute);*/
    }
	private class VPEventActivityAdapter extends BaseAdapter{
		private VPEvent myAdapterEvent;
		private Context myAdapterContext;
		private List<VPEvent> myListAdapterEvent;
		private LayoutInflater myLayoutInflater;
		private View myAdapterListView;
		private TextView mytvTitle, mytvID, mytvStartDate, mytvEndDate;
		private int myLastSelectedPosition;

		public VPEventActivityAdapter(List<VPEvent> _myListEvent,
				Context _vpEventActivity, String _path) {
			// TODO Auto-generated constructor stub
			myListAdapterEvent = _myListEvent;
			myAdapterContext = _vpEventActivity;
			myLayoutInflater = (LayoutInflater)myAdapterContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			myLastSelectedPosition = -1;
		}

		public void setMyLastSelectedPostition(int myPositionCurrentOfList) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return myListAdapterEvent.size();
		}

		@Override
		public VPEvent getItem(int arg0) {
			// TODO Auto-generated method stub
			return myListAdapterEvent.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return myListAdapterEvent.get(arg0).getVpeId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			convertView = null;
			myListView = null;
			
			final int posTemp = position;			
			
			if (convertView == null){
				myAdapterListView = (ListView) new View(myAdapterContext);
				myAdapterListView = myLayoutInflater.inflate(R.layout.activity_vpevent_sub, null);
				
				mytvID  = (TextView)myListView.findViewById(R.id.tvEventID);
				mytvTitle = (TextView)myListView.findViewById(R.id.tvEventTitle);
				mytvStartDate  = (TextView)myListView.findViewById(R.id.tvEventStart);
				mytvEndDate = (TextView)myListView.findViewById(R.id.tvEventEnd);
				myAdapterEvent = new VPEvent();
				myAdapterEvent = getItem(position);
				
				mytvID.setText(myAdapterEvent.getVpeId());
				mytvTitle.setText(myAdapterEvent.getVpeTitle());
										
				myAdapterListView.setBackgroundResource(R.drawable.background_shape_white);
				
				if(position == myLastSelectedPosition)
				{
					myListView.setBackgroundResource(R.drawable.list_selector_pressed);
				}
				
			}					
			
			return myListView;
		}
		
	}
	
	}

